package tech.aistar.util;

import okhttp3.*;
import org.apache.commons.codec.binary.Base64;

import java.io.IOException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CompilerUtil {
    static final String APP_ID = "3";
    static final String APP_SECRET = "af89663a11f3cc59fc5544daff9dcc02";

    public String complier(String code,String lang) {

        /**
         * 这里的code 要用于计算sign值，必须是还原成明文。
         * 部分 sign 异常原因是因为 code 值为 base64加密串或encodeURIComponent未被还原造成的
         */
        String sign = sign(code);

        // post 请求
        FormBody body = new FormBody.Builder()
                .add("appId", APP_ID)
                .add("sign", sign)
                .add("lang", lang)
                .add("code", URLEncoder.encode(Base64.encodeBase64String(code.getBytes())))
                .build();
        String result = null;
        try {
            result = post("http://jsrun.net/api/run", body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.print(result);
        return result;
    }

    static String sign(String code) {
        return md5(code + APP_SECRET);
    }

    static String md5(String str) {
        /**
         * Spring 中建议直接使用 DigestUtils.md5DigestAsHex() 计算md5值
         */
        try {
            byte[] secretBytes = null;
            secretBytes = MessageDigest.getInstance("md5").digest(str.getBytes());

            String md5code = new BigInteger(1, secretBytes).toString(16);
            for (int i = 0; i < 32 - md5code.length(); i++) {
                md5code = "0" + md5code;
            }
            return md5code;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
    }

    static String post(String url, RequestBody body) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(body).build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

